# encoding: utf-8
import os
from datetime import datetime

from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

import models
import memcache_def

class BaseRequestHandler(webapp.RequestHandler):
	"""Base classs"""
	count_per_footer = memcache_def.get_count_per_footer_memcache()
	def generate(self, template_name, template_values={}):
		site_name = memcache_def.get_site_name_memcache()
		values = {
			'site_name': site_name
		}
		values.update(template_values)
		directory = os.path.dirname(__file__)
		path = os.path.join(directory, os.path.join('templates', template_name))
		self.response.out.write(template.render(path, values))

class main_base(BaseRequestHandler):
	def get(self):
		#显示首页默认内容
		default_content = models.Content.all().filter('type','default').get()
		if default_content:
			time_date = datetime.strftime(default_content.time_date,'%A %H:%M:%S %m月%d日 %Y年')
			default_content_value = default_content.content
		else:
			time_date = '没有日期'
			default_content_value = '暂时没有内容'
		values = {
			'default_content': default_content_value,
			'time_date': time_date
		}
		#显示首页默认内容 END
		#页脚分页
		bookmark_id = self.request.get('b')
		if bookmark_id:
			bookmark_key = models.Content.get_by_id(int(bookmark_id)).key()
			articles = models.Content.all().order("-__key__").filter('type','article').filter('__key__ <=',bookmark_key).fetch(int(self.count_per_footer)+1)
			pre_articles = models.Content.all().order('__key__').filter('type','article').filter('__key__ >',bookmark_key).fetch(int(self.count_per_footer))
		else:
			articles = models.Content.all().order('-__key__').filter('type','article').fetch(int(self.count_per_footer)+1)
			pre_articles = None
		if len(articles) == int(self.count_per_footer)+1:
			values_page = {
				'next_page': articles[int(self.count_per_footer)]
			}
			values.update(values_page)
		if (pre_articles) and (len(pre_articles)>0):
			values_page_2 = {
				'pre_page': pre_articles[-1]
			}
			values.update(values_page_2)
		value_ar_cn = {
			'article_contents': articles[:int(self.count_per_footer)]
		}
		values.update(value_ar_cn)
		#页脚分页 END
		self.generate('main_base.html',values)

class article_page(BaseRequestHandler):
	def get(self):
		str_id = self.request.path[1:-13]
		article_content = models.Content.get_by_id(int(str_id))
		time_date = datetime.strftime(article_content.time_date,'%A %H:%M:%S %m月%d日 %Y年')
		b_key = article_content.key()
		half_count = int(int(self.count_per_footer)/2)
		right_footer = models.Content.all().order("-__key__").filter('type =','article').filter("__key__ <",b_key).fetch(half_count)
		left_footer = models.Content.all().order("__key__").filter('type =','article').filter("__key__ >",b_key).fetch(half_count)
		if len(right_footer) < half_count:
			left_footer = models.Content.all().order("__key__").filter('type =','article').filter("__key__ >",b_key).fetch(half_count+(half_count-len(right_footer)))
		if len(left_footer) < half_count:
			right_footer = models.Content.all().order("-__key__").filter('type =','article').filter("__key__ <",b_key).fetch(half_count+(half_count-len(left_footer)))

		left_footer.reverse()
		value = {
			'article_content': article_content,
			'time_date': time_date,
			'left_footers': left_footer,
			'right_footers': right_footer
		}
		self.generate('article_base.html',value)

class show_image(webapp.RequestHandler):
	def get(self):
		img_path = self.request.path
		img_str_key =  img_path[1:-6]
		image = db.get(db.Key(img_str_key))
		self.response.headers['Content-Type'] = 'image/png'
		self.response.out.write(image.content)

class error(BaseRequestHandler):
	def get(self):
		self.generate('error_base.html')

def main():
	application = webapp.WSGIApplication([
		('/$', main_base),
		('/.*html$', article_page),
		('/.*image$', show_image),
		('/.*', error)
	],debug=True)
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
